<?php
/*
 * 加密方式
 * @author     Mark <zhaody901@126.com>
 * @copyright  Copyright (c) 2013 lemon team
 * @version    $Id: 18274ef748e122e9a3edb705e0cdf5e16f025856 $
 * @time       14-2-7 上午10:26
 */
class Crypt {


	/**
	 * 加密
	 * @param        $txt
	 * @param string $key
	 * @return mixed
	 */
	public static function encode($txt, $key = '') {
		$rnd = md5(microtime());
		$len = strlen($txt);
		$ren = strlen($rnd);
		$ctr = 0;
		$str = '';
		for ($i = 0; $i < $len; $i++) {
			$ctr = $ctr == $ren ? 0 : $ctr;
			$str .= $rnd[$ctr] . ($txt[$i] ^ $rnd[$ctr++]);
		}
		return str_replace('=', '', base64_encode(self::_ke($str, $key)));
	}

	/**
	 * 解密
	 * @param        $txt
	 * @param string $key
	 * @return string
	 */
	public static function decode($txt, $key = '') {
		$txt = self::_ke(base64_decode($txt), $key);
		$len = strlen($txt);
		$str = '';
		for ($i = 0; $i < $len; $i++) {
			$tmp = $txt[$i];
			$str .= $txt[++$i] ^ $tmp;
		}
		return $str;
	}

	/**
	 * 加密动作, 验证时候使用
	 * 用来验证是否本IP操作
	 *      $action = Crypt::action('action')
	 * @param $action
	 * @return string
	 */
	public static function action($action) {
		global $DT_IP;
		return md5(md5($action . DT_KEY . $DT_IP));
	}

	/**
	 * @param $txt
	 * @param $key
	 * @return string
	 */
	private static function _ke($txt, $key) {
		$key = md5($key);
		$len = strlen($txt);
		$ken = strlen($key);
		$ctr = 0;
		$str = '';
		for ($i = 0; $i < $len; $i++) {
			$ctr = $ctr == $ken ? 0 : $ctr;
			$str .= $txt[$i] ^ $key[$ctr++];
		}
		return $str;
	}
}